import { ReqPage } from "@/api/interface";
import { Applet } from "@/api/interface/iot";
import { serviceList, serviceRemove, serviceStart, serviceStop, serviceUpgrade } from "@/api/modules/service/service";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { MessageType } from "@/enums/messageEnum";
import { SvcType } from "@/enums/statusEnum";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import "../detail.scss";
import AppletImg from "./../../../../assets/images/applet/applet.png";
import DockerImg from "./../../../../assets/images/applet/docker.png";
import ServiceDetailDialog from "./serviceDetailDialog";
import RunnintStatus from "@/components/Sansan/Status/RunnintStatus";
import LoggerDialog from "@/views/system/services/components/loggerDialog";
import PublicTag from "@/components/Sansan/Status/PublicTag";
import mittBus from "@/utils/mittBus";
export default defineComponent({
	props: {
		btns: {
			type: Array,
			default() {
				return [];
			}
		},
		nodeSn: String,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		// const btnList = ref<any>([
		// 	{ path: "add", menuName: "添加服务", btnClass: "primary" },
		// 	{ menuName: "更新", path: "mod" },
		// 	{ menuName: "刪除", path: "del" },
		// 	{ menuName: "启动", path: "restart" },
		// 	{ menuName: "停止", path: "stop" }
		// ]);
		// 表格配置项
		let columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "status", label: proxy?.$t("appletservice.tablist_label.status"), width: "120px", isShow: !!props.nodeSn },
			// { prop: "extend", label: "继承应用配置", width: "120px", isShow: !!props.nodeSn },
			{ prop: "name", label: proxy?.$t("appletservice.tablist_label.name"), width: "180px" },
			{ prop: "key", label: proxy?.$t("appletservice.tablist_label.key"), width: "80px" },
			{ prop: "bin", label: proxy?.$t("appletservice.tablist_label.bin"), width: "100px" },
			{ prop: "svcType", label: proxy?.$t("appletservice.tablist_label.svc_type"), width: "130px" },
			{ prop: "arg", label: proxy?.$t("appletservice.tablist_label.arg"), width: "180px" },
			{ prop: "path", label: proxy?.$t("appletservice.tablist_label.path") },
			// { prop: "version", label: "版本", width: "100px" },
			// { prop: "latestVersion", label: "最新版本", width: "100px" },
			{ prop: "createTime", label: proxy?.$t("appletservice.tablist_label.create_time"), width: "180px" },
			{ prop: "updateTime", label: proxy?.$t("appletservice.tablist_label.update_time"), width: "180px" },
			{
				prop: "operate",
				label: proxy?.$t("appletservice.tablist_label.operate"),
				fixed: "right",
				width: props.nodeSn ? "300" : "140"
			}
		];
		const btnList = ref<any[]>([]);
		watchEffect(() => {
			btnList.value = (props.btns || []).filter((item: any) => item.btnGroup == "6");
			columns = columns.map((item: any) => {
				if (item.prop == "operate") {
					item.isShow = !!btnList.value.length;
				}
				return item;
			});
		});
		const initParam = reactive<ReqPage>({
			pageIndex: 0,
			pageSize: 20,
			appId: props.nodeSn ? props.detail.appId : props.detail.id,
			appInstanceKey: props.nodeSn ? props.detail.appInstanceId.split(".")[0] : "",
			template: 1
		});
		if (props.nodeSn) {
			delete initParam.template;
		}

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		//初始化服务列表
		const getTableList = async (params: any) => {
			return serviceList(params);
		};
		onMounted(async () => {});
		const proTable = ref<any>();
		const submitDel = async (dataList: any[]) => {
			if (!dataList.length) {
				showMsg(proxy?.$t("appletservice.msg.del"), MessageType.warning);
				return;
			}
			confirm({ content: proxy?.$t("appletservice.confirm.del") }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await serviceRemove({
					id: dataList.map((item: any) => item.id).join(",")
				});
				let ok = showTips(code, `删除服务`, message);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.reset();
				}
			});
		};
		const clickBtn = async (fn: string, scope?: any) => {
			let selectList = scope?.row ? [scope?.row] : scope?.selectList || proTable.value.selectedList || [];
			switch (fn) {
				case "add":
					detailDialog.detail = { appInstanceId: props.detail.appInstanceId, svcType: "bin" };
					detailDialog.title = proxy?.$t("appletservice.dialog_title.add");
					detailDialog.visible = true;
					break;
				case "del":
					submitDel(selectList);
					break;
				case "update":
					update(selectList);
					break;
				case "upgrade":
					if (selectList.length != 1) {
						showMsg(proxy?.$t("appletservice.msg.upgrade"), MessageType.warning);
						return;
					}
					// if (props.nodeSn) {
					// 	update(selectList);
					// } else {
					detailDialog.detail = { ...selectList[0] };
					detailDialog.title = proxy?.$t("appletservice.dialog_title.upgrade");
					detailDialog.visible = true;
					// }

					break;
				case "logger":
					if (selectList && selectList.length != 1) {
						showMsg(proxy?.$t("appletservice.msg.logger"), MessageType.warning);
						return;
					}
					let info = { ...(selectList && selectList[0]) };
					loggerDialog.title = "【" + info.name + "】运行日志";
					loggerDialog.detail = info;
					loggerDialog.visible = true;
					break;
				case "stop":
					if (selectList && selectList.length != 1) {
						showMsg(proxy?.$t("appletservice.msg.stop"), MessageType.warning);
						return;
					}
					stop(selectList);
					break;
				case "start":
					if (selectList && selectList.length != 1) {
						showMsg(proxy?.$t("appletservice.msg.start"), MessageType.warning);
						return;
					}
					start(selectList);
					break;
			}
		};
		const update = async (data: any) => {
			confirm({ content: proxy?.$t("appletservice.confirm.update") }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await serviceUpgrade({
					id: data[0].id
				});
				let ok = showTips(code, `升级服务`, message);
				if (ok) {
					proTable.value.reset();
				}
			});
		};
		const start = async (data: any) => {
			if (!data[0]) {
				showMsg(proxy?.$t("appletservice.msg.service"), MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStart({ id: data[0].id });
				let ok = showTips(code, "服务启动", message);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.getTableList();
				}
			}, 1000);
		};
		const stop = async (data: any) => {
			if (!data[0]) {
				showMsg(proxy?.$t("appletservice.msg.service"), MessageType.warning);
				return;
			}
			setTimeout(async () => {
				let { code, message } = await serviceStop({ id: data[0].id });
				let ok = showTips(code, "服务停止", message);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.getTableList();
				}
			}, 1000);
		};

		const submitAdd = async () => {
			detailDialog.visible = false;
			proTable.value.getTableList();
		};
		const detailDialog = reactive<any>({
			detail: {},
			title: "",
			visible: false
		});
		const options = ref(SvcType);
		const loggerDialog = reactive<any>({
			detail: {},
			title: proxy?.$t("appletservice.dialog_title.logger"),
			visible: false
		});
		onBeforeMount(() => {
			mittBus.on("refreshAppletDetail", () => {
				proTable.value.reset();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshAppletDetail");
		});
		return () => {
			return (
				<div class="p-6 shadow mt-4" style="border: 1px solid #eee;">
					<div class="flex items-center justify-between w-full pb-4">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>{proxy?.$t("appletservice.tab_title.service")}</span>
						</div>
						<div class="">
							{btnList.value
								?.filter((item: any) => {
									if (!props.nodeSn) {
										return item.path != "del" && item.path != "upgrade" && item.path != "start" && item.path != "stop";
									} else {
										return (
											item.path != "del" &&
											item.path != "upgrade" &&
											item.path != "add" &&
											item.path != "start" &&
											item.path != "stop"
										);
									}
								})
								.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								})}
						</div>
					</div>
					<ServiceDetailDialog
						width="600"
						v-model:visible={detailDialog.visible}
						title={detailDialog.title}
						onSubmit={submitAdd}
						detail={detailDialog.detail}
						appId={initParam.appId}
						nodeSn={props.nodeSn}
					></ServiceDetailDialog>
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={["关闭"]}
					/>
					<ProTable
						ref={proTable}
						custSearch={false}
						showHeader={false}
						title={btnList.value.length ? "" : proxy?.$t("appletservice.tab_title.service_manage")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return btnList.value
									?.filter((item: any) => item.path != "del")
									.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.type}>
												{item.title}
											</el-button>
										);
									});
							},
							extend: (scope: any) => {
								return scope.row.extend ? (
									<PublicTag
										v-model={scope.row.extend}
										types={{ yes: "success", no: "danger" }}
										labels={{ yes: "是", no: "否" }}
									/>
								) : (
									""
								);
							},
							status: (scope: any) => {
								return <RunnintStatus v-model={scope.row.status} />;
							},
							name: (scope: any) => {
								return (
									<div class="flex justify-center items-center">
										<span class="pl-2">{scope.row.name}</span>
									</div>
								);
							},
							svcType: (scope: any) => {
								return (
									<div class="flex item-center">
										<img style="height:18px;" src={scope.row.svcType == "docker" ? DockerImg : AppletImg}></img>
										<span class="pl-2">
											{scope.row.svcType && options.value.filter((item: any) => item.value == scope.row.svcType)[0].label}
										</span>
									</div>
								);
							},
							path: (scope: any) => {
								return <div>{JSON.stringify(scope.row.path).slice(1, -1)}</div>;
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							updateTime: (scope: any) => {
								return dataFormat("datetime", scope.row.updateTime);
							},
							operate: (scope: any) => {
								return (
									<>
										{scope.row.nodeSn ? (
											<>
												<el-link type="primary" link class="iconfont iconbx-cog" onClick={() => clickBtn("start", scope)}>
													{proxy?.$t("appletservice.link.start")}
												</el-link>
												<el-link type="danger" link class="iconfont iconbx-stop-circle" onClick={() => clickBtn("stop", scope)}>
													{proxy?.$t("appletservice.link.stop")}
												</el-link>
												<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("update", scope)}>
													{proxy?.$t("appletservice.link.up")}
												</el-link>
												<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
													{proxy?.$t("appletservice.link.logger")}
												</el-link>
											</>
										) : (
											""
										)}
										{btnList.value.map((item: any) => {
											return item.path == "del" && !props.nodeSn ? (
												<el-link type="danger" link class="iconfont icontrash-2" onClick={() => clickBtn("del", scope)}>
													{proxy?.$t("appletservice.link.delete")}
												</el-link>
											) : item.path == "upgrade" ? (
												<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("upgrade", scope)}>
													{proxy?.$t("appletservice.link.edit")}
												</el-link>
											) : null;
										})}
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle={proxy?.$t("appletservice.empty.subtitle")}
											btnText={proxy?.$t("appletservice.empty.btn_text")}
											showButton={false}
											onAdd={(scope: any) => clickBtn("add", scope)}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
